package util;

import session.RoleSession;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import java.util.List;
import java.util.Objects;
import java.util.Vector;

public class TetureJsonComboBox extends JComboBox<String> {
	private final Vector<String> items;
	private int selectedIndex = 0;

	public TetureJsonComboBox(Vector<String> items) {
		super(items);
		this.items = items;
		init();
	}

	private void init() {
		setEditable(true);

		JTextField f = (JTextField) getEditor().getEditorComponent();
		f.getDocument().addDocumentListener(new DocumentListener() {
			@Override
			public void insertUpdate(DocumentEvent e) {
				updateMapKey(e);
			}

			@Override
			public void removeUpdate(DocumentEvent e) {
				updateMapKey(e);
			}

			@Override
			public void changedUpdate(DocumentEvent e) {
			}
		});
	}

	private void updateMapKey(DocumentEvent e) {
		// 改变选定项的情况排除，但这里要考虑-1的情况
		if (getSelectedIndex() != selectedIndex) {
			if (getSelectedIndex() != -1) {
				selectedIndex = getSelectedIndex();
				return;
			}
		}

		String oldKey = items.get(selectedIndex);
		try {
			if (getSelectedIndex() != -1) {
				selectedIndex = getSelectedIndex();
			}
			String newKey = e.getDocument().getText(0, e.getDocument().getLength());
			items.set(selectedIndex, newKey);
			if (!Objects.equals(oldKey, newKey)) {
				List<String[]> val = RoleSession.TEXTURE_JSON_ITEMS.get(oldKey);
				RoleSession.TEXTURE_JSON_ITEMS.put(oldKey, null);
				RoleSession.TEXTURE_JSON_ITEMS.put(newKey, val);
			}
		} catch (BadLocationException ex) {
			throw new RuntimeException(ex);
		}
	}

	public Vector<String> getItems() {
		return items;
	}
}
